from django.shortcuts import render
from django.views import View
from django import http
from apps.areas.models import Area
from apps.users.models import Address
import json, re
from utility.views import LoginRequiredJsonMixin
from django.core.cache import cache


# Create your views here.


class ProvinceView(View):
    """省份地区"""

    def get(self, request):

        province_list = cache.get('province_list')
        if province_list:
            return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'province_list': province_list})

        try:
            # provinces = Area.objects.filter(parent__isnull=True)
            provinces = Area.objects.filter(parent=None)

            province_list = []
            for province in provinces:
                province_list.append({
                    'id': province.id,
                    'name': province.name
                })
            cache.set('province_list', province_list, 3600 * 24)
        except Exception as e:

            return http.JsonResponse({'code': 400, 'errmsg': '获取失败'})

        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'province_list': province_list})


class CtiyView(View):
    """城市地区"""

    def get(self, request, id):
        # 获取当前ID的市
        ctiy_list = cache.get('subs %s' % id)
        if ctiy_list:
            return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'sub_data': ctiy_list})
        province = Area.objects.get(id=id)

        # 获取当前id的区或县
        ctiys = Area.objects.filter(parent=id)

        ctiy_list = []

        for ctiy in ctiys:
            ctiy_list.append({
                'id': ctiy.id,
                'name': ctiy.name
            })

        sub_data = {
            'id': province.id,
            'name': province.name,
            'subs': ctiy_list
        }
        cache.set('subs %s' % id, sub_data, 3600 * 24)

        # }

        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'sub_data': sub_data})
